﻿package main {
	import common.Debug;
	import flash.display.DisplayObject;
	import flash.display.Loader;
	import flash.display.LoaderInfo;
	import flash.display.MovieClip;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.net.URLRequest;
	
	/**
	 * TODO メモリリークを防ぐ
	 */
	public class MoviePlayer {
		
		public function MoviePlayer() {
			sprite = new Sprite();
			sprite.graphics.beginFill(0xFFFFFF);
			sprite.graphics.drawRect(0, 0, 640, 480);
			sprite.graphics.endFill();
			
			var loader:Loader = new Loader();
			loader.contentLoaderInfo.addEventListener(Event.INIT, initHandler);
			loader.load(new URLRequest("http://www.youtube.com/apiplayer?version=3"));
		}
		
		private var id:String = "9R5Rf5Js6Eo";
		
		private var sprite:Sprite;
		public function getSprite():Sprite {
			return sprite;
		}
		
		private var ytp:Object;
		
		public function play():void {
			ytp.playVideo();
		}
		public function getPlayerState():int {
			return ytp.getPlayerState();
		}
		public function stop():void {
			ytp.stopVideo();
		}
		
		private function initHandler(event:Event):void {
			ytp = Loader(LoaderInfo(event.currentTarget).loader).content;
			sprite.addChild(ytp as DisplayObject);
			ytp.addEventListener("onReady", onReadyHandler);
			ytp.addEventListener("onError", onErrorHandler);
			ytp.addEventListener("onStateChange", onStateChangeHandler);
			ytp.addEventListener("onPlaybackQualityChange", onPlaybackQualityChangeHandler);
		}
		private function onReadyHandler(event:Event):void {
			ytp.setSize(sprite.width, sprite.height);
			ytp.cueVideoById(id);
		}
		private function onErrorHandler(event:Event):void {
			Debug.t("error", Object(event).data);
		}
		private function onStateChangeHandler(newState:Number):void {
			Debug.t("state", newState);
		}
		private function onPlaybackQualityChangeHandler(event:Event):void {
			Debug.t("quality", Object(event).data);
		}
	}
	
}